const Router = require('koa-router');
const { Task } = require('../models/tasks');
const router = new Router();

router.post('/', async (ctx) => {
    const { user_id, text } = ctx.request.body;
    Task.addTask(user_id, text);
    ctx.body = { success: true };
});

// 删除所有任务
router.delete('/:user_id', async (ctx) => {
    try {
        const userId = ctx.params.user_id;
        Task.deleteAllTasks(userId);
        ctx.body = { success: true };
    } catch (error) {
        console.error(error); // 在控制台记录错误信息
        ctx.status = 500; // 设置响应状态为 500
        ctx.body = { error: 'Failed to delete tasks.' }; // 返回错误信息
    }
});

// 获取用户的所有任务
router.get('/:user_id', async (ctx) => {
    const tasks = Task.getTasks(ctx.params.user_id);
    ctx.body = { tasks };
});

// 删除单个任务
router.delete('/:task_id', async (ctx) => {
    const taskId = ctx.params.task_id;
    console.log(`Received delete request for task ID: ${taskId}`); // 打印接收到的请求
    try {
        Task.deleteTask(taskId); // 确保 deleteTask 方法正常
        ctx.body = { success: true }; // 返回成功的响应
        console.log(`Deleted task with ID: ${taskId}`);
    } catch (error) {
        console.error(`Error deleting task: ${error.message}`);
        ctx.status = 500; // 设置响应状态为 500
        ctx.body = { error: 'Failed to delete task.' }; // 返回错误信息
    }
});

// 更新任务
router.put('/:task_id', async (ctx) => {
    const { text } = ctx.request.body;
    Task.updateTask(ctx.params.task_id, text);
    ctx.body = { success: true };
});

module.exports = router;